import axios from 'axios'
import store from '@/store'
import {Message, Notice} from 'view-design'

class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl
  }

  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {}
    }
    return config
  }

  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 权限信息
      if (store.getters.token) {
        config.headers['Authorization'] = store.getters.token
      }
      return config
    }, error => {
      console.log(error) // for debug
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      // 数据源格式
      // code data msg success
      const data = res.data;
      if (data.code && data.code !== 200) {
        Notice.error({title: 'error', desc: error, duration: 5 * 1000});
      } else {
        return data
      }
    }, error => {
      switch (error.response.status) {
        case 401:
        case 403:
        case 405:
          Notice.error({title: 'error', desc: '拒绝访问，请联系管理员', duration: 5 * 1000});
          break;
        case 500:
          Notice.error({title: 'error', desc: '服务器错误，请联系管理员', duration: 5 * 1000});
          break;
        /*default:
          Notice.error({title: 'error', desc: error, duration: 5 * 1000});*/
      }
      return Promise.reject(error)
    })
  }

  request(options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}

export default HttpRequest
